package com.appengine.utils;

import java.util.ArrayList;
import java.util.Calendar;
import org.json.JSONObject;
import com.datatypes.AEuser;
import com.datatypes.FriendsZone;
import com.datatypes.OfflineLogs;
import com.datatypes.Track;
import com.datatypes.User;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookUtils;
import com.facebook.android.SessionStore;
import com.sporteamws.MainMenu;
import com.sporteamws.SharedPref;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class AeLoadingCenter {

	// setup base url of appengine server
	private static String BaseURL = "https://sporteamws.appspot.com/";

	// setup main query url
	private static String GetUserURL = BaseURL + "GetUserInfo";

	// setup loading bar theme
	private static int LoadingBarTheme = 2;

	// setup ics enum code
	private static int ICSApiCode = 14;

	// load android user from appengine
	public static User LoadAndroidUserFromAE(String facebookID,
			String access_token, Context c) {
		JSONObject json = null;
		AEuser user = null;
		String reqURL = null;
		ArrayList<String> friends = null;
		if (!SharedPref.GotNetworkConnection)
			return SavingAndLoadingCenter.loadUser(facebookID, c);

		try {

			if (access_token.length() == 0) // get already defined user from AE
			{
				reqURL = GetUserURL + "?request_type=get_user"
						+ "&facebook_ID=" + facebookID;
			} else // send a request to create new user and store on AE
			{
				reqURL = GetUserURL + "?request_type=get_user"
						+ "&facebook_ID=" + facebookID + "&access_token="
						+ access_token;
			}
			// read json object from app engine servers
			json = JsonUtils.readJsonFromUrl(reqURL);
			if (json == null)
				throw new Exception();

			String userStr = (String) json.get("user");
			String friendStr = (String) json.get("friends");

			user = GsonUtils.ConvertGsonStringToAEuser(userStr);
			friends = GsonUtils.ConvertGsonStringToFriends(friendStr);

		} catch (Exception e) {
			SharedPref.GotNetworkConnection = false;
			UIUtils.PrintToast(c, "no internet connection", Toast.LENGTH_LONG);
			Log.e("error on loading user", e.toString());
			return SavingAndLoadingCenter.loadUser(facebookID, c);
		}

		if (user == null) {
			Log.e("user is null", reqURL);
			return null;
		} else {
			user.SetFriends(friends);
		}

		FriendsZone fz = null;
		if (user.GetSporTeamFriends() != null) {
			fz = new FriendsZone(user.GetSporTeamFriends());
		} else {
			fz = new FriendsZone();

		}

		/** image delete **/
		SavingAndLoadingCenter.deleteFriendsImages(fz.getFriends(), c);
		SavingAndLoadingCenter.deleteMyImage(facebookID, c);

		SavingAndLoadingCenter.saveFriendsZone(facebookID, fz, c);

		// update network connectivity
		SharedPref.GotNetworkConnection = true;

		return new User(user);

	}

	// sync all data with appengine
	public static AEuser SyncWithAE(String facebookID, Context c) {
		JSONObject json = null;
		AEuser ae_user = null;
		long lastUpdatedTrack = SavingAndLoadingCenter.loadLastUpdatedTrack(c);

		try {
			String reqURL = GetUserURL + "?request_type=get_user_for_sync"
					+ "&facebook_ID=" + facebookID + "&last_updated_track="
					+ lastUpdatedTrack;

			// read json object from app engine servers
			json = JsonUtils.readJsonFromUrl(reqURL);
			if (json == null)
				throw new Exception();

			/* --- get all essential information from server --- */

			// get user json
			String userStr = (String) json.get("user");

			// get tracks json
			String tracksStr = (String) json.get("tracks");

			// get activities json
			String actsStr = (String) json.get("activities");

			// convert user back from Gson string
			ae_user = GsonUtils.ConvertGsonStringToAEuser(userStr);

			// load tracks
			ae_user.SetTracks(GsonUtils.ConvertGsonStringToTracks(tracksStr));

			// load activities
			ae_user.SetActivities(GsonUtils
					.ConvertGsonStringToActivities(actsStr));

		} catch (Exception e) {
			SharedPref.GotNetworkConnection = false;
			Log.e("error in sync", e.toString());
			UIUtils.PrintToast(c, "no internet connection", Toast.LENGTH_LONG);
			return null;
		}

		return ae_user;
	}

	private static ArrayList<Track> LoadTracksFromAE(String facebookID,
			Context c) {
		JSONObject json = null;
		ArrayList<Track> tracks = null;

		if (!SharedPref.GotNetworkConnection)
			return (ArrayList<Track>) SavingAndLoadingCenter.loadUserTracks(
					facebookID, c).getTracksList();

		// load last updated track date from internal storage
		long lastUpdatedTrack = SavingAndLoadingCenter.loadLastUpdatedTrack(c);

		try {
			String reqURL = GetUserURL + "?request_type=get_tracks"
					+ "&facebook_ID=" + facebookID + "&last_updated_track="
					+ lastUpdatedTrack;

			// read json object from app engine servers
			json = JsonUtils.readJsonFromUrl(reqURL);
			if (json == null)
				throw new Exception();

			String tracksStr = (String) json.get("tracks");
			tracks = GsonUtils.ConvertGsonStringToTracks(tracksStr);

		} catch (Exception e) {
			SharedPref.GotNetworkConnection = false;
			UIUtils.PrintToast(c, "no internet connection", Toast.LENGTH_LONG);
			Log.e("error on loading tracks", e.toString());
		}

		long MaxUpdatedTime = 0;

		// get last updated track from current tracks
		if (tracks != null) {
			for (Track t : tracks) {
				if (t.getDate() > MaxUpdatedTime)
					MaxUpdatedTime = t.getDate();
			}
		}

		// save new last updated track on internal storage
		SavingAndLoadingCenter.saveLastUpdatedTrack(c, MaxUpdatedTime);

		// update network connectivity
		SharedPref.GotNetworkConnection = true;

		return tracks;

	}

	private static ArrayList<com.datatypes.Activity> LoadActivitiesFromAE(
			String facebookID, Context c) {
		JSONObject json = null;
		ArrayList<com.datatypes.Activity> activities = null;

		if (!SharedPref.GotNetworkConnection)
			return (ArrayList<com.datatypes.Activity>) SavingAndLoadingCenter
					.loadActivityTracks(facebookID, c).getActivityList();

		try {
			String reqURL = GetUserURL + "?request_type=get_activities"
					+ "&facebook_ID=" + facebookID;

			// read json object from app engine servers
			json = JsonUtils.readJsonFromUrl(reqURL);
			if (json == null)
				throw new Exception();

			String actsStr = (String) json.get("activities");

			activities = GsonUtils.ConvertGsonStringToActivities(actsStr);
		} catch (Exception e) {
			SharedPref.GotNetworkConnection = false;
			UIUtils.PrintToast(c, "no internet connection", Toast.LENGTH_LONG);
			Log.e("error on loading activities", e.toString());
		}

		// update network connectivity
		SharedPref.GotNetworkConnection = true;

		return activities;

	}

	private static ArrayList<String> LoadFriendsFromAE(String facebookID,
			Context c) {
		JSONObject json = null;
		ArrayList<String> friends = null;

		if (!SharedPref.GotNetworkConnection)
			return null; // TODO thing what TODO

		try {
			String reqURL = GetUserURL + "?request_type=get_friends"
					+ "&facebook_ID=" + facebookID;

			// read json object from app engine servers
			json = JsonUtils.readJsonFromUrl(reqURL);

			String friendsStr = (String) json.get("friends");

			friends = GsonUtils.ConvertGsonStringToFriends(friendsStr);
		} catch (Exception e) {
			SharedPref.GotNetworkConnection = false;
			Log.e("error on loading friends", e.toString());
		}

		// update network connectivity
		SharedPref.GotNetworkConnection = true;

		return friends;

	}

	public static void LoadActivities(String facebook_id, Intent intent,
			Context c) {
		new LoadingTask("load_activities", facebook_id, intent, (Activity) c,
				true).execute();
	}

	public static void LoadTracks(String facebook_id, Intent intent, Context c) {
		new LoadingTask("load_tracks", facebook_id, intent, (Activity) c, true)
				.execute();
	}

	public static void LoadAEuser(String facebook_id, Context c) {
		new LoadingTask("load_user", facebook_id, (Activity) c, true).execute();
	}

	public static void LoadAEuser(String facebook_id, Intent intent, Context c) {
		new LoadingTask("load_user", facebook_id, intent, (Activity) c, true)
				.execute();
	}

	public static void LoadMainFromIntro(Facebook mFacebook, Context c,
			TextView tvLoading) {
		new LoadingTask("load_main", mFacebook, tvLoading, (Activity) c, false)
				.execute();
	}

	public static void LoadMainFromFBLogin(Facebook mFacebook, Context c,
			TextView tvLoading, String access_token) {
		new LoadingTask("load_main", mFacebook, tvLoading, (Activity) c,
				access_token, true).execute();
	}

	public static void CheckInternetConnecion() {
		new LoadingTask("check_connection", false);
	}

	public static void LoadProfilePic(String facebook_id, Context c,
			ImageView profilePic, ProgressBar picLoadingPB) {
		new LoadingTask("load_profile_pic", facebook_id, profilePic,
				picLoadingPB, (Activity) c, false).execute();
	}

	public static void SendTrack(Track t, String facebook_id, Context c) {
		new LoadingTask("send_track", t, facebook_id, (Activity) c, true)
				.execute();
	}

	public static void SendActivity(com.datatypes.Activity act, Context c) {
		new LoadingTask("send_activity", act, (Activity) c, true).execute();
	}

	public static void SendActivityOnBackground(com.datatypes.Activity act,
			Context c) {
		new LoadingTask("send_activity", act, (Activity) c, true).execute();
	}

	public static void PostTrackOnFB(Facebook mFacebook, Track t, Context c) {
		new LoadingTask("post_track", mFacebook, t, (Activity) c, true)
				.execute();
	}

	public static void PostTracWithImgkOnFB(Facebook mFacebook, Track t,
			Bitmap bitmap, Context c) {
		new LoadingTask("post_track_with_img", mFacebook, t, bitmap,
				(Activity) c, false).execute();
	}

	public static void PostLonelyStatusOnFB(Facebook mFacebook, Context c) {
		new LoadingTask("post_lonely_status", mFacebook, (Activity) c, true)
				.execute();
	}

	private static class LoadingTask extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog dialog;
		private Context context;
		private ProgressBar picLoadingPB;
		private String loading_command;
		private String facebook_id;
		private Intent intent;
		private Facebook mFacebook;
		private TextView tvLoading;
		private boolean showPB;
		private ImageView profilePic;
		private Track track;
		private com.datatypes.Activity act;
		private String access_token;
		private Bitmap bitmap;

		public LoadingTask(String loading_command, boolean showPB) {
			this.loading_command = loading_command;
			this.showPB = showPB;
		}

		public LoadingTask(String loading_command, String facebook_id,
				Intent intent, Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.facebook_id = facebook_id;
			this.context = activity;
			this.intent = intent;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, String facebook_id,
				Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.facebook_id = facebook_id;
			this.context = activity;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, Facebook mFacebook,
				TextView tvLoading, Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.context = activity;
			this.mFacebook = mFacebook;
			this.access_token = "";
			this.tvLoading = tvLoading;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, String facebook_id,
				ImageView profilePic, ProgressBar picLoadingPB,
				Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.context = activity;
			this.picLoadingPB = picLoadingPB;
			this.facebook_id = facebook_id;
			this.profilePic = profilePic;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, Track track,
				String facebook_id, Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.facebook_id = facebook_id;
			this.context = activity;
			this.track = track;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, com.datatypes.Activity act,
				Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.context = activity;
			this.act = act;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, Facebook mFacebook,
				TextView tvLoading, Activity c, String access_token,
				boolean showPB) {
			this.loading_command = loading_command;
			this.context = c;
			this.mFacebook = mFacebook;
			this.tvLoading = tvLoading;
			this.showPB = showPB;
			this.access_token = access_token;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, Facebook mFacebook, Track t,
				Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.context = activity;
			this.mFacebook = mFacebook;
			this.track = t;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, Facebook mFacebook, Track t,
				Bitmap bitmap, Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.context = activity;
			this.mFacebook = mFacebook;
			this.track = t;
			this.bitmap = bitmap;
			this.showPB = showPB;
			SetupProgressBar();
		}

		public LoadingTask(String loading_command, Facebook mFacebook,
				Activity activity, boolean showPB) {
			this.loading_command = loading_command;
			this.context = activity;
			this.mFacebook = mFacebook;
			this.showPB = showPB;
			SetupProgressBar();
		}

		protected void SetupProgressBar() {

			// new progress bar for android 4 and up
			int currentapiVersion = android.os.Build.VERSION.SDK_INT;
			if (currentapiVersion >= ICSApiCode) {
				this.dialog = new ProgressDialog(this.context, LoadingBarTheme);
			} else {
				this.dialog = new ProgressDialog(this.context);
			}

			// this.dialog = new ProgressDialog(this.context);

		}

		protected void onPreExecute() {
			if (loading_command.equals("load_activities")) {
				this.dialog.setMessage("loading activities..");
			} else if (loading_command.equals("load_tracks")) {
				this.dialog.setMessage("loading tracks..");
			} else if (loading_command.equals("load_user")) {
				this.dialog.setMessage("syncing data..");
			} else if (loading_command.equals("load_main")) {
				this.dialog.setMessage("loading user information..");
			} else if (loading_command.equals("send_track")) {
				this.dialog.setMessage("sending track..");
			} else if (loading_command.equals("send_activity")) {
				this.dialog.setMessage("sending activity..");
			} else if (loading_command.equals("post_track")) {
				this.dialog.setMessage("posting to facebook..");
			} else if (loading_command.equals("post_track_with_img")) {
				this.dialog.setMessage("posting to facebook..");
			} else if (loading_command.equals("post_lonely_status")) {
				this.dialog.setMessage("posting to facebook..");
			}

			// show progress bar in case loading is not from intro screen
			if (this.showPB)
				this.dialog.show();
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			// hide progress bar
			try {
				if (dialog.isShowing()) {
					dialog.dismiss();
				}
			} catch (Exception e) {
				Log.e("error", "error on dialog dismiss");
			}

			if (loading_command.equals("load_activities")) {
				if (this.intent != null && this.context != null)
					this.context.startActivity(this.intent);
			} else if (loading_command.equals("load_tracks")) {
				if (this.intent != null && this.context != null)
					this.context.startActivity(this.intent);
			} else if (loading_command.equals("load_user")) {
				if (this.intent != null && this.context != null)
					this.context.startActivity(this.intent);
			} else if (loading_command.equals("load_user")) {
				if (this.intent != null && this.context != null)
					this.context.startActivity(this.intent);
			} else if (loading_command.equals("load_main")) {
				if (this.intent != null && this.context != null)
					this.context.startActivity(this.intent);
			} else if (loading_command.equals("load_profile_pic")) {
				UIUtils.hideProgressBar(this.picLoadingPB, this.context);
			} else if (loading_command.equals("check_connection")) {
				// TODO think what to do
			}
		}

		protected Boolean doInBackground(final String... args) {
			try {
				if (loading_command.equals("load_user")) {
					HandleUserLoading();
				} else if (loading_command.equals("load_activities")) {
					HandleActivityLoad();
				} else if (loading_command.equals("load_tracks")) {
					HandleTracksLoad();
				} else if (loading_command.equals("load_main")) {
					HandleMainLoad();
				} else if (loading_command.equals("load_profile_pic")) {
					HandleProfilePicLoad();
				} else if (loading_command.equals("send_track")) {
					HandleSendTrack();
				} else if (loading_command.equals("send_activity")) {
					HandleSendActivity();
				} else if (loading_command.equals("check_connection")) {
					UpdateNetworkConnectivity();
				} else if (loading_command.equals("post_track")) {
					HandlePostTrack();
				} else if (loading_command.equals("post_track_with_img")) {
					HandlePostTrackWithImg();
				} else if (loading_command.equals("post_lonely_status")) {
					HandlePostLonelyStatus();
				}

				return true;
			} catch (Exception e) {
				Log.e("error on backround loading", e.toString());
				return false;
			}
		}

		// posting lonely status to facebook
		private void HandlePostLonelyStatus() {
			FacebookUtils.PostLonelyStatus(this.mFacebook, this.context);

		}

		protected void HandlePostTrack() {
			boolean PostSuccess = FacebookUtils.PostTrackToFacebook(
					this.mFacebook, this.track, this.context);
			if (!PostSuccess) {
				// in case post failed, save in logs
			}
		}

		protected void HandlePostTrackWithImg() {
			boolean PostSuccess = FacebookUtils.PostTrackWithImgToFacebook(
					this.mFacebook, this.bitmap, this.track, this.context);
			if (!PostSuccess) {
				// in case post failed, save in logs
			}
		}

		protected void HandleSendTrack() {
			boolean sentSuccessfully = UserUtils.SendTrack(this.track,
					this.facebook_id);
			if (!sentSuccessfully) {
				OfflineLogs oll = SavingAndLoadingCenter.loadOfflineLogs(
						this.facebook_id, this.context);
				oll.addLog(new com.datatypes.Log(this.track.getDate(), true));
				SavingAndLoadingCenter.saveOfflineLogs(this.facebook_id, oll,
						this.context);
			}

		}

		protected void HandleSendActivity() {

			boolean sentSuccessfully = UserUtils.SendActivityToUser(this.act);

			if (!sentSuccessfully) {
				OfflineLogs oll = SavingAndLoadingCenter.loadOfflineLogs(
						SharedPref.facebookID, this.context);
				oll.addLog(new com.datatypes.Log(this.act.getActivity_id(),
						true));
				SavingAndLoadingCenter.saveOfflineLogs(SharedPref.facebookID,
						oll, this.context);
			}

		}

		protected void HandleUserLoading() {

			UserUtils.SyncUserData(this.facebook_id, this.context);

			/*
			 * AEuser ae_user; User user; User loaded_user =
			 * SavingAndLoadingCenter.loadUser( this.facebook_id, this.context);
			 * if (loaded_user == null) { // download user from appengine
			 * ae_user = SyncWithAE(this.facebook_id, this.context);
			 * 
			 * if (ae_user == null) return; else user = new User(ae_user); }
			 * else { ae_user = SyncWithAE(this.facebook_id, this.context); if
			 * (ae_user == null) return ; else user = new User(ae_user);
			 * 
			 * UserUtils.HandleLogs(this.facebook_id, this.context); }
			 * 
			 * // update internal storage UserUtils.CacheUserData(ae_user, user,
			 * this.context);
			 */
		}

		protected void HandleActivityLoad() {
			// load activities

			long current_time = Calendar.getInstance().getTime().getTime();
			ArrayList<com.datatypes.Activity> activities = null;
			// load activities in case 20 minutes past since last update
			if (current_time - SharedPref.lastUpdate > 1000 * 61 * 20) {
				activities = AeLoadingCenter.LoadActivitiesFromAE(facebook_id,
						this.context);
				SharedPref.lastUpdate = current_time;
			}

			if (activities != null) {

				/*
				 * --- used the 20 minutes timeout between loading // update
				 * server that all activities are synced for
				 * (com.datatypes.Activity act : activities) {
				 * act.setSynced(true);
				 * UserUtils.UpdateActivitySynced(this.facebook_id,
				 * act.getActivity_id(), act.isSynced()); }
				 */

				// save on cache
				SavingAndLoadingCenter.saveActivityTracks(this.facebook_id,
						activities, this.context);
			}

		}

		protected void HandleTracksLoad() {

			// load last updated track date from internal storage
			long lastUpdatedTrack = SavingAndLoadingCenter
					.loadLastUpdatedTrack(this.context);

			ArrayList<Track> tracks = null;

			// load tracks
			if (lastUpdatedTrack == 0) { // in case first time entered or
											// cleared cache
				tracks = AeLoadingCenter.LoadTracksFromAE(this.facebook_id,
						this.context);

			}

			// save on cache
			if (tracks != null) {

				// save tracks on cache
				SavingAndLoadingCenter.saveUserTracks(this.facebook_id, tracks,
						this.context);
			}

		}

		protected void HandleMainLoad() {

			if (PrevSessionExists() == false)// in case no previous session was
												// found
			{
				// set intent to open facebook login activity
				this.intent = new Intent(this.context,
						com.facebook.android.Login.class);
			} else {

				// run sync on background thread TODO think if necessery
				// ExecuteBackgroundSync(this.facebook_id, this.context);

				// load activities on background thread
				// ExecuteBackgroundActivityLoad();

				// load tracks on background thread
				// ExecuteBackgroundTracksLoad();

				if (this.tvLoading != null)
					UIUtils.SetTextOnUIthread(this.context, this.tvLoading,
							"loading user information..");

				SharedPref.facebookID = this.facebook_id;

				// load user from appengine and save on internal storage
				User user = AeLoadingCenter.LoadAndroidUserFromAE(
						this.facebook_id, this.access_token, this.context);

				// save user in internal storage
				SavingAndLoadingCenter.saveUser(user, this.context);

				// handle logs in case of a valid internet connection
				if (SharedPref.GotNetworkConnection)
					UserUtils.HandleLogs(this.facebook_id, this.context);

				/* c2dm disabled right now ------------------------
				 * register to c2dm servers on background thread if
				 * (SharedPref.GotNetworkConnection)
				 * AuthenticationUtil.C2dmRegister(this.context);
				 */

				// set intent to open main menu activity
				this.intent = new Intent(this.context, MainMenu.class);
			}

		}

		// returns true if facebook ID was found on storage or false otherwise
		protected boolean PrevSessionExists() {

			// scan for facebook ID saved on disk
			String loadedFacebookID = null;

			if (!this.showPB) // in case this is a loading from intro session
				loadedFacebookID = SavingAndLoadingCenter
						.loadFB_ID(this.context);

			if (loadedFacebookID == null && SharedPref.GotNetworkConnection)
			// in case no facebook ID on disk
			{
				if (this.tvLoading != null)
					UIUtils.SetTextOnUIthread(this.context, this.tvLoading,
							"restoring facebook session..");

				// restore previous session from facebook
				SessionStore.restore(mFacebook, this.context);

				if (mFacebook.isSessionValid()) // in case previous session was
												// found
				{
					JSONObject json = null;
					try {
						if (this.tvLoading != null)
							UIUtils.SetTextOnUIthread(this.context,
									this.tvLoading,
									"fetching data from facebook..");

						// get facebook id from facebook servers
						json = FacebookUtils.parseJson(mFacebook.request("me"));

						// get id from json
						this.facebook_id = json.getString("id");

						// update shared preferences
						SharedPref.facebookID = this.facebook_id;

						// override internal storage with new facebook id
						SavingAndLoadingCenter.saveFB_ID(this.context,
								this.facebook_id);

					} catch (Exception e) {
						Log.e("error on main loading", e.toString());
						return false;
					}
				} else
					return false;
			} else if (loadedFacebookID != null) // in case previous session was
													// found on disk
			{
				this.facebook_id = loadedFacebookID;
				if (this.tvLoading != null)
					UIUtils.SetTextOnUIthread(this.context, this.tvLoading,
							"loading previous session..");

			} else if (!SharedPref.GotNetworkConnection)// in case no internet
														// connection and no
														// previous session
														// found
			{
				if (this.tvLoading != null)
					UIUtils.SetTextOnUIthread(this.context, this.tvLoading,
							"must login with facebook");

				// UIUtils.showAlertDialog(this.context,
				// "Houston, We've Got a Problem",
				// "you must login with facebook first to use SporTeam");
			}

			return true;
		}

		protected void HandleProfilePicLoad() {
			Bitmap img = SavingAndLoadingCenter.loadFriendImage(
					this.facebook_id, this.context);

			if (SharedPref.GotNetworkConnection)
				UIUtils.showProgressBar(this.picLoadingPB, this.context);

			if (img == null && SharedPref.GotNetworkConnection) {
				img = FacebookUtils.GetProfilePic(this.facebook_id, "normal");
				SavingAndLoadingCenter.saveFriendImage(this.facebook_id, img,
						this.context);
			}

			// TODO save picture in normal mode too
			if (SharedPref.GotNetworkConnection) {
				img = FacebookUtils.GetProfilePic(this.facebook_id, "normal");
				if (img.getHeight() > 120)
					img = Bitmap.createBitmap(img, 0, 0, img.getWidth(), 120);
				else
					img = Bitmap.createScaledBitmap(img, img.getWidth(), 120,
							false);
				UIUtils.SetBitmapPic(this.profilePic, img, this.context);
			}
		}

		protected void ExecuteBackgroundSync(String facebookID, Context c) {
			final String f_fID = facebookID;
			final Context f_c = c;

			if (!SharedPref.GotNetworkConnection)
				return;

			Thread t = new Thread() {
				@Override
				public void run() {
					UserUtils.SyncUserData(f_fID, f_c);
				}
			};

			t.start();
		}

		protected void ExecuteBackgroundActivityLoad() {
			if (!SharedPref.GotNetworkConnection)
				return;

			Thread t = new Thread() {
				@Override
				public void run() {
					HandleActivityLoad();
				}
			};

			t.start();
		}

		protected void ExecuteBackgroundTracksLoad() {
			if (!SharedPref.GotNetworkConnection)
				return;

			Thread t = new Thread() {
				@Override
				public void run() {
					HandleTracksLoad();
				}
			};

			t.start();
		}

		protected void UpdateNetworkConnectivity() {
			try {
				String reqURL = GetUserURL + "?request_type=get_tracks"
						+ "&facebook_ID=" + "1507604362"
						+ "&last_updated_track=" + "0";

				// read json object from app engine servers
				JSONObject json = JsonUtils.readJsonFromUrl(reqURL);
				if (json == null)
					throw new Exception();

			} catch (Exception e) {
				SharedPref.GotNetworkConnection = false;
			}

			SharedPref.GotNetworkConnection = true;

		}

	}
}
